#include "allinformationwindow.h"
#include "ui_allinformationwindow.h"

AllInformationWindow::AllInformationWindow(QTcpSocket * clientSocket,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AllInformationWindow)
    , clientSocket(clientSocket)
{
    ui->setupUi(this);

    QPixmap pixmap("../../../resource/3.jpg");

    // 创建一个QPalette实例
    QPalette palette;
    palette.setBrush(QPalette::Window, pixmap);

    // 设置窗口的调色板
    this->setPalette(palette);

    // 设置窗口标题
    this->setWindowTitle("历史病历");
    //this->ui->label->setStyleSheet("QLabel { background-color: white; }");

    // get MedicalRecords
    QString medicalRecordsQueryStr = "SELECT * FROM MedicalRecords WHERE patient_id = "+QString::number(currentUserID)+";";
    clientSocket->write(medicalRecordsQueryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000); // 等待数据写入完成，超时时间为1秒

    if (clientSocket->waitForReadyRead(3000)) { // 等待数据接收，超时时间为3秒
        // 接收数据
        QByteArray data = clientSocket->readAll();

        // 将数据转换为字符串
        QString receivedData = QString::fromUtf8(data);

        // 检查接收到的数据是否为"failed"
        if (receivedData == "failed") {
            ;
        } else {
            QStringList items = receivedData.split('\n');
            ui->MedicalRecordsWidget->setColumnCount(4);
            ui->MedicalRecordsWidget->setRowCount(items.size()-1);
            ui->MedicalRecordsWidget->setHorizontalHeaderLabels(QStringList() <<  "Date" << "Diagnosis" << "Instructions" << "Prescription");
            int rowCnt=0;
            for (const QString &item : items) {
                qDebug()<<item;
                QStringList atomItems = item.split('|');
                if(atomItems.size()<5)
                    break;
                for(int i =2;i<6;i++){
                    QTableWidgetItem *tableWidgetItem = new QTableWidgetItem(atomItems[i]);
                    ui->MedicalRecordsWidget->setItem(rowCnt,i-2,tableWidgetItem);
                }
                rowCnt++;
            }
        }
        // 设置大小策略
        ui->MedicalRecordsWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        // 自动调整列宽和行高
        ui->MedicalRecordsWidget->resizeColumnsToContents();
        ui->MedicalRecordsWidget->resizeRowsToContents();

        // 计算合适的宽度和高度
        int width = ui->MedicalRecordsWidget->horizontalHeader()->length() + 15;
        int height = ui->MedicalRecordsWidget->verticalHeader()->length() +23;

        ui->MedicalRecordsWidget->resize(width,height);
    } else {
        // 如果超时未接收到数据
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
        exit(999);
    }
}

void AllInformationWindow::on_BackButton_clicked(){
    emit back();
}

AllInformationWindow::~AllInformationWindow()
{
    delete ui;
}
